﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using WinnerCMS.Model;
using EntityFramework.Extensions;
namespace WinnerCMS.Data
{
    /// <summary>
    /// 权限
    /// </summary>
    public class RightsDal
    {
        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="modelId"></param>
        public void Add(string modelId)
        {
            using (Entities db = new Entities())
            {
                List<Right> list = (from x in db.Rights
                                        where x.ModelId == modelId
                                        orderby x.RootId, x.OrderId
                                        select x).ToList();

                string newId = Guid.NewGuid().ToString();

                var maxModel = db.Models.OrderByDescending(x => x.Id).First();

                int maxRootId = db.Rights.Where(x => x.ModelId != "").Max(x => x.RootId) + 1;


                for (int i = 0; i < list.Count; i++)
                {
                    var v = list[i];
                    if (i == 0)
                    {
                        Right r = new Right
                        {
                            Id = newId,
                            ModelId = maxModel.Id.ToString(),
                            Name = maxModel.ModelName,
                            Code = v.Code,
                            RootId = maxRootId,
                            OrderId = v.OrderId,
                            ParentId = string.Empty,
                            IsAdmin = true
                        };

                        db.Rights.Add(r);

                    }
                    else
                    {
                        Right r = new Right
                        {
                            Id = Guid.NewGuid().ToString(),
                            ModelId = maxModel.Id.ToString(),
                            Name = v.Name,
                            Code = v.Code,
                            RootId = maxRootId,
                            OrderId = v.OrderId,
                            ParentId = newId,
                            IsAdmin = true
                        };

                        db.Rights.Add(r);

                    }
                }
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 删除模型下的权限
        /// </summary>
        /// <param name="modelId"></param>
        public void Delete(string modelId)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Rights where x.ModelId == modelId select x;
                q.ToList().ForEach(x => db.Rights.Remove(x));

                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 根权限
        /// </summary>
        /// <param name="isAdmin"></param>
        /// <returns></returns>
        public IList<Right> GetRootRights(bool isAdmin)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Rights
                        where x.IsAdmin == isAdmin && x.ParentId == ""
                        orderby x.RootId ascending
                        select x;

                return q.ToList();
            }
        }
        /// <summary>
        /// 获取管理员权限
        /// </summary>
        /// <param name="rootId"></param>
        /// <param name="isAdmin"></param>
        /// <returns></returns>
        public IList<Right> GetRights(int rootId, bool isAdmin)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Rights
                        where x.IsAdmin == isAdmin && x.RootId == rootId && x.ParentId != ""
                        orderby x.OrderId ascending
                        select x;
                return q.ToList();
            }
        }
        /// <summary>
        /// 角色的所有权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public IList<Right> GetRoleRights(int roleId)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Rights
                        where x.Roles.Any(y => y.Id == roleId)
                        select x;


                return q.ToList();
            }
        }
        /// <summary>
        /// 获取用户包含的权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public IList<Right> GetRights(int userId)
        {
            using (Entities db = new Entities())
            {
                var query = db.Rights.Where(x => x.Roles.Any(y => y.Users.Any(z => z.Id == userId)));

                return query.Distinct().ToList();
            }
        }

        /// <summary>
        /// 给用户最终分配权限
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="rightIds"></param>
        public void Distribute(int userid, IEnumerable<string> rightIds)
        {
            using (Entities db = new Entities())
            {
                db.Configuration.LazyLoadingEnabled = true;
                var user = db.Users.First(x => x.Id == userid);

                var allrights = db.Rights.ToList();
                allrights.ForEach(x => user.Rights.Remove(x));

                var rights = allrights.Where(x => rightIds.Contains(x.Id)).ToArray();
                foreach (var r in rights)
                {
                    user.Rights.Add(r);
                }
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 给角色最终分配权限
        /// </summary>
        /// <param name="roleid"></param>
        public void DistributeForRole(int roleid)
        {
            using (Entities db = new Entities())
            {
                db.Database.ExecuteSqlCommand(@"DELETE  FROM CMS_UserRight
WHERE   UserId IN ( SELECT  UserID
                    FROM    CMS_UserRole
                    WHERE   RoleID = {0} )
INSERT  INTO CMS_UserRight
        ( UserId ,
          RightId
        )
        SELECT  UR.UserID AS UserId ,
                RR.RightId
        FROM    CMS_UserRole UR
                INNER JOIN CMS_RoleRight RR ON UR.RoleID = RR.RoleID
        WHERE   UR.RoleID = {0}", roleid);
            }
        }
    }
}
